package org.amphiprion.descentv2assistant;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.amphiprion.descentv2assistant.entity.Ability;
import org.amphiprion.descentv2assistant.entity.Archetype;
import org.amphiprion.descentv2assistant.entity.Condition;
import org.amphiprion.descentv2assistant.entity.Entity;
import org.amphiprion.descentv2assistant.entity.GameSession;
import org.amphiprion.descentv2assistant.entity.Language;
import org.amphiprion.descentv2assistant.entity.Product;
import org.amphiprion.descentv2assistant.entity.Trait;
import org.amphiprion.descentv2assistant.util.cache.ImageCache;
import org.amphiprion.descentv2assistant.util.cache.ImageFetcher;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;

public class App {

	public static GameSession currentGameSession;
	public static List<Archetype> archetypes;
	public static List<Ability> abilities;
	public static List<Product> products;
	public static List<Trait> traits;
	public static List<Language> languages;
	public static List<Condition> conditions;

	private static ImageFetcher mImageFetcher;

	public static int dpiToPixels(Context paramContext, int paramInt) {
		return (int) (0.5F + paramInt * paramContext.getResources().getDisplayMetrics().density);
	}

	public static boolean isPhone(Context paramContext) {
		return !isTablet(paramContext);
	}

	public static boolean isTablet(Context paramContext) {
		if ((0xF & paramContext.getResources().getConfiguration().screenLayout) >= 3) {
			return true;
		} else {
			return false;
		}
	}

	public static void hideKeyboard(Context context, EditText editText) {
		InputMethodManager localInputMethodManager = (InputMethodManager) context.getSystemService("input_method");
		if (localInputMethodManager != null) {
			localInputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
		}
	}

	public static boolean isNetworkAvail(Context context) {
		NetworkInfo localNetworkInfo = ((ConnectivityManager) context.getSystemService("connectivity")).getActiveNetworkInfo();
		if ((localNetworkInfo == null) || (!localNetworkInfo.isConnected())) {
			return false;
		} else {
			return true;
		}
	}

	public static String getValue(String paramString) {

		if ((paramString != null) && (!paramString.equals("null")) && (!TextUtils.isEmpty(paramString))) {
			return paramString.trim();
		}
		return "";
	}

	public static void setImage(ImageView img, Entity entity) {
		setImage(img, "/images/" + entity.getClass().getSimpleName() + "/", entity.getId());
	}

	public static void setImage(ImageView img, Entity entity, FragmentManager manager) {
		// setImage(img, "/images/" + entity.getClass().getSimpleName() + "/", entity.getId());
		if (mImageFetcher == null) {
			ImageCache.ImageCacheParams localImageCacheParams = new ImageCache.ImageCacheParams(img.getContext(), "tempimgs");
			localImageCacheParams.setMemCacheSizePercent(0.8F);
			mImageFetcher = new ImageFetcher(img.getContext(), img.getWidth(), img.getHeight());
			mImageFetcher.addImageCache(manager, localImageCacheParams);
		}

		String localPath = "/images/" + entity.getClass().getSimpleName() + "/";
		String imageNameWithoutExt = entity.getId();

		String path = Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + localPath;

		File f = new File(path + imageNameWithoutExt + ".jpg");
		if (f.exists()) {
			mImageFetcher.loadImage("FILE:" + f.getAbsolutePath(), img);
		} else {
			f = new File(path + imageNameWithoutExt + ".png");
			if (f.exists()) {
				mImageFetcher.loadImage("FILE:" + f.getAbsolutePath(), img);
			} else {
				mImageFetcher.loadImage("CLASSPATH:" + localPath + imageNameWithoutExt + ".png", img);
			}
		}
		// if (bitmap == null) {
		// img.setVisibility(View.GONE);
		// } else {
		// img.setVisibility(View.VISIBLE);
		// img.setImageBitmap(bitmap);
		// }

	}

	public static void setImage(ImageView img, String localPath, String imageNameWithoutExt) {
		String path = Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + localPath;

		Bitmap bitmap = null;
		File f = new File(path + imageNameWithoutExt + ".jpg");
		if (f.exists()) {
			bitmap = BitmapFactory.decodeFile(f.toString());
		} else {
			f = new File(path + imageNameWithoutExt + ".png");
			if (f.exists()) {
				bitmap = BitmapFactory.decodeFile(f.toString());
			} else {
				InputStream is = App.class.getResourceAsStream(localPath + imageNameWithoutExt + ".png");
				if (is != null) {
					bitmap = BitmapFactory.decodeStream(is);
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		if (bitmap == null) {
			img.setVisibility(View.GONE);
		} else {
			img.setVisibility(View.VISIBLE);
			img.setImageBitmap(bitmap);
		}

	}

	public static void createDirectoryStructure() {
		File f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/images/Archetype");
		f.mkdirs();
		f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/images/DiceAttack");
		f.mkdirs();
		f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/images/DiceDefense");
		f.mkdirs();
		f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/images/Hero");
		f.mkdirs();
		f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/images/Monster");
		f.mkdirs();
		f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/images/Lieutenant");
		f.mkdirs();
		f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/images/Trait");
		f.mkdirs();
		f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/photos");
		f.mkdirs();

	}

	public static void restoreXmls() {

		App.copyResource("/abilities.xml");
		App.copyResource("/archetypes.xml");
		App.copyResource("/heroes.xml");
		App.copyResource("/monsters.xml");
		App.copyResource("/languages.xml");
		App.copyResource("/products.xml");
		App.copyResource("/traits.xml");
		App.copyResource("/conditions.xml");
		App.copyResource("/lieutenants.xml");

		clearInMemoryXmls();
	}

	public static void clearInMemoryXmls() {
		App.abilities = null;
		App.archetypes = null;
		App.conditions = null;
		App.languages = null;
		App.products = null;
		App.traits = null;
	}

	public static void copyResource(String resource) {
		try {
			byte[] bytes = new byte[1024];
			InputStream is = App.class.getResourceAsStream(resource);
			if (is != null) {
				FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + resource);
				int lenght = 0;
				while ((lenght = is.read(bytes)) > 0) {
					fos.write(bytes, 0, lenght);
				}
				fos.close();
				is.close();
			} else {
				Log.w(ApplicationConstants.PACKAGE, "copyResource: " + resource + " not found.");
			}
		} catch (Throwable e) {
			Log.e(ApplicationConstants.PACKAGE, "copyResource", e);
		}
	}
}
